#!/usr/bin/env bash

progname=`basename "${0}"`

usage() {
	echo "usage: ${progname} { start | stop | restart | status }" >&2
	exit 1
}

while getopts ":" arg; do
	case "${arg}" in
	?)
		usage
		;;
	esac
done

case "$#" in
0)
	mode=start
	;;
1)
	case "${1}" in
	start|stop|restart|status)
		mode="${1}"
		;;
	*)
		usage
		;;
	esac
	;;
*)
	usage
	;;
esac

ps --no-headers -fC node 2>/dev/null | grep 'fantasmatakia'
[ "${mode}" == "status" ] && exit 0

cd skiser/log || exit 2

pidFile="skiser.pid"
if [ -s "${pidFile}" ]; then
	pid=`cat "${pidFile}"`
	kill ${pid} || exit 2
	while [ -e /proc/${pid} ]; do sleep 1; done
fi

[ "${mode}" == "stop" ] && exit 0

{
	mv skiser.out skiser1.out
	mv skiser.err skiser1.err
} 2>/dev/null

cd ..
nohup node main.js fantasmatakia >log/skiser.out 2>log/skiser.err &
sleep 1 && ps --no-headers -fC node
